package net.mihome.app.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.bean.ActiveList;
import net.mihome.app.bean.AdvertList;
import net.mihome.app.bean.Article;
import net.mihome.app.bean.Banner;
import net.mihome.app.bean.Barcode;
import net.mihome.app.bean.BlogCommentList;
import net.mihome.app.bean.BlogList;
import net.mihome.app.bean.ChatMsgEntity;
import net.mihome.app.bean.ChatRoom;
import net.mihome.app.bean.CommentList;
import net.mihome.app.bean.CommunityList;
import net.mihome.app.bean.FavoriteList;
import net.mihome.app.bean.FriendList;
import net.mihome.app.bean.MessageList;
import net.mihome.app.bean.MyInformation;
import net.mihome.app.bean.News;
import net.mihome.app.bean.NewsList;
import net.mihome.app.bean.NewsType;
import net.mihome.app.bean.Notice;
import net.mihome.app.bean.Post;
import net.mihome.app.bean.PostList;
import net.mihome.app.bean.Report;
import net.mihome.app.bean.Result;
import net.mihome.app.bean.RssNews;
import net.mihome.app.bean.RssResource;
import net.mihome.app.bean.RssType;
import net.mihome.app.bean.SearchList;
import net.mihome.app.bean.Shop;
import net.mihome.app.bean.ShopMenu;
import net.mihome.app.bean.Software;
import net.mihome.app.bean.SoftwareCatalogList;
import net.mihome.app.bean.SoftwareList;
import net.mihome.app.bean.Tweet;
import net.mihome.app.bean.TweetList;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.Update;
import net.mihome.app.bean.User;
import net.mihome.app.bean.UserInformation;
import net.mihome.app.bean.UserPrepertie;
import net.mihome.app.bean.WellcomeImage;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.FileUtils;
import net.mihome.app.common.ImageUtils;
import net.mihome.app.common.StringUtils;
import net.mihome.app.utils.LoginResponseHandler;
import net.mihome.app.utils.MD5;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * API客户端接口：用于访问网络数据
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class ApiClient {

	public static final String UTF_8 = "UTF-8";
	public static final String DESC = "descend";
	public static final String ASC = "ascend";
	private final static int TIMEOUT_CONNECTION = 20000;
	private final static int TIMEOUT_SOCKET = 20000;
	private final static int RETRY_TIME = 3;

	private static String appCookie;
	private static String appUserAgent;
	public static void cleanCookie() {
		appCookie = "";
	}
	
	private static String getCookie(AppContext appContext) {
		if(appCookie == null || appCookie == "") {
			appCookie = appContext.getProperty("cookie");
		}
		return appCookie;
	}
	
	private static String getUserAgent(AppContext appContext) {
		if(appUserAgent == null || appUserAgent == "") {
			StringBuilder ua = new StringBuilder("OSChina.NET");
			ua.append('/'+appContext.getPackageInfo().versionName+'_'+appContext.getPackageInfo().versionCode);//App版本
			ua.append("/Android");//手机系统平台
			ua.append("/"+android.os.Build.VERSION.RELEASE);//手机系统版本
			ua.append("/"+android.os.Build.MODEL); //手机型号
			ua.append("/"+appContext.getAppId());//客户端唯一标识
			appUserAgent = ua.toString();
		}
		return appUserAgent;
	}
	
	private static HttpClient getHttpClient() {        
        HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间 
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}	
	
	private static GetMethod getHttpGet(String url, String cookie, String userAgent) {
		GetMethod httpGet = new GetMethod(url);
		// 设置 请求超时时间
		httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpGet.setRequestHeader("Host", URLs.HOST);
		httpGet.setRequestHeader("Connection","Keep-Alive");
		httpGet.setRequestHeader("Cookie", cookie);
		httpGet.setRequestHeader("User-Agent", userAgent);
		return httpGet;
	}
	
	private static PostMethod getHttpPost(String url, String cookie, String userAgent) {
		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Host", URLs.HOST);
		httpPost.setRequestHeader("Connection","Keep-Alive");
		httpPost.setRequestHeader("Cookie", cookie);
		httpPost.setRequestHeader("User-Agent", userAgent);
		return httpPost;
	}
	
	private static String _MakeURL(String p_url, Map<String, Object> params) {
		StringBuilder url = new StringBuilder(p_url);
		if(url.indexOf("?")<0)
			url.append('?');

		for(String name : params.keySet()){
			url.append('&');
			url.append(name);
			url.append('=');
			url.append(String.valueOf(params.get(name)));
			//不做URLEncoder处理
			//url.append(URLEncoder.encode(String.valueOf(params.get(name)), UTF_8));
		}

		return url.toString().replace("?&", "?");
	}
	public static String http_get_string(AppContext appContext, String url) throws AppException, Exception{
		return URLs.readFromInputStream(http_get(appContext, url));
	}
	/**
	 * get请求URL
	 * @param url
	 * @throws AppException 
	 */
	private static InputStream http_get(AppContext appContext, String url) throws AppException {	
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, cookie, userAgent);			
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				responseBody = httpGet.getResponseBodyAsString();
				break;				
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		
		//responseBody = responseBody.replaceAll("\\p{Cntrl}", "\r\n");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		return new ByteArrayInputStream(responseBody.getBytes());
	}
	/**
	 * get请求URL
	 * @param url
	 * @throws AppException 
	 */
	private static ResponsePojo http_get_responsePojo(AppContext appContext, String url) throws AppException {	
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, cookie, userAgent);			
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				else if(statusCode == HttpStatus.SC_OK) 
		        {
		            Cookie[] cookies = httpClient.getState().getCookies();
		            String tmpcookies = "";
		            for (Cookie ck : cookies) {
		                tmpcookies += ck.toString()+";";
		            }
		            //保存cookie   
	        		if(appContext != null && tmpcookies != ""){
	        			appContext.setProperty("cookie", tmpcookies);
	        			appCookie = tmpcookies;
	        		}
		        }
				responseBody = httpGet.getResponseBodyAsString();
				break;				
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		
		//responseBody = responseBody.replaceAll("\\p{Cntrl}", "\r\n");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		try {
			return URLs.fromInputstream(new ByteArrayInputStream(responseBody.getBytes()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw AppException.http(AppException.TYPE_JSON);
		}
	}
	/**
	 * 公用post方法
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException
	 */
	private static InputStream _post(AppContext appContext, String url, Map<String, Object> params, Map<String,File> files) throws AppException {
		//System.out.println("post_url==> "+url);
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		PostMethod httpPost = null;
		
		//post表单参数处理
		int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size());
		Part[] parts = new Part[length];
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        int i = 0;
        if(params != null)
        for(String name : params.keySet()){
        	parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8);
            nvps.add(new BasicNameValuePair(name, String.valueOf(params.get(name))));
        	//System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
        }
        if(files != null)
        for(String file : files.keySet()){
        	try {
				parts[i++] = new FilePart(file, files.get(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
        	//System.out.println("post_key_file==> "+file);
        }
		
		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpPost = getHttpPost(url, cookie, userAgent);
		        httpPost.setRequestEntity(new MultipartRequestEntity(parts,httpPost.getParams()));
		        int statusCode = httpClient.executeMethod(httpPost);
		        if(statusCode != HttpStatus.SC_OK) 
		        {
		        	throw AppException.http(statusCode);
		        }
		        else if(statusCode == HttpStatus.SC_OK) 
		        {
		            Cookie[] cookies = httpClient.getState().getCookies();
		            String tmpcookies = "";
		            for (Cookie ck : cookies) {
		                tmpcookies += ck.toString()+";";
		            }
		            //保存cookie   
	        		if(appContext != null && tmpcookies != ""){
	        			appContext.setProperty("cookie", tmpcookies);
	        			appCookie = tmpcookies;
	        		}
		        }
		     	responseBody = httpPost.getResponseBodyAsString();
		        //System.out.println("XMLDATA=====>"+responseBody);
		     	break;	     	
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpPost.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
        
        responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
        return new ByteArrayInputStream(responseBody.getBytes());
	}
	
	/**
	 * post请求URL
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException 
	 * @throws IOException 
	 * @throws  
	 */
	private static Result http_post(AppContext appContext, String url, Map<String, Object> params, Map<String,File> files) throws AppException, IOException {
        return Result.parse(_post(appContext, url, params, files));  
	}	
	private static ResponsePojo http_post_responsePojo(AppContext appContext, String url, Map<String, Object> params, Map<String,File> files) throws Exception {
		return URLs.fromInputstream(_post(appContext, url, params, files));
	}	
	/**
	 * 获取网络图片
	 * @param url
	 * @return
	 */
	public static Bitmap getNetBitmap(String url) throws AppException {
		HttpClient httpClient = null;
		GetMethod httpGet = null;
		Bitmap bitmap = null;
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, null, null);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
		        InputStream inStream = httpGet.getResponseBodyAsStream();
		        bitmap = BitmapFactory.decodeStream(inStream);
		        inStream.close();
		        break;
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			}catch (Exception e) {
                time++;
                if(time < RETRY_TIME) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {}
                    continue;
                }
                // 发生网络异常
                e.printStackTrace();
                throw AppException.network(e);
            }
            finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		return bitmap;
	}
	
	/**
	 * 检查版本更新
	 * @param url
	 * @return
	 */
	public static Update checkVersion(AppContext appContext) throws AppException {
		try{

			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, URLs.MIHOME_UPDATE_ANDROID);
			return Update.parse(responsePojo.getData());		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 检查是否有可下载的欢迎界面图片
	 * @param appContext
	 * @return
	 * @throws AppException
	 */
    public static String APPSTART_IMAGE_BACKGROUND_KEY="appstart_image_background_key";
	public static void checkBackGround(AppContext appContext) throws AppException {
		try{
			WellcomeImage update = WellcomeImage.parse(http_get_responsePojo(appContext, URLs.MIHOME_USER_BACKGROUND_IMG));
            String imageUrl=appContext.getProperty(APPSTART_IMAGE_BACKGROUND_KEY);
            if(imageUrl==null){
                if(update!=null&&update.getDownloadUrl()!=null&&!"".equals(update.getDownloadUrl())){
                    appContext.setProperty(APPSTART_IMAGE_BACKGROUND_KEY,update.getDownloadUrl());
                }
            }else{
                if(!imageUrl.equals(update.getDownloadUrl())){
                    appContext.setProperty(APPSTART_IMAGE_BACKGROUND_KEY,update.getDownloadUrl());
                }
            }
//			String filePath = FileUtils.getAppCache(appContext, "welcomeback");
//			// 如果没有图片的链接地址则返回
//			if(update.isUpdate()) {
//				if(StringUtils.isEmpty(update.getDownloadUrl())) {
//					return;
//				}
//				String url = update.getDownloadUrl();
//				String fileName=MD5.Md5(url);
////				String fileName = update.getStartDate().replace("-", "") + "-" + update.getEndDate().replace("-", "");
//				List<File> files = FileUtils.listPathFiles(filePath);
//				boolean isExits=FileUtils.checkFilePathExists(filePath + fileName + ".png");
//				if (isExits) {
//						return;
//				}
//				Bitmap photo = getNetBitmap(url);
//				ImageUtils.saveImageToSD(appContext,
//						filePath + fileName + ".png", photo, 100);
//			} else {
//				FileUtils.clearFileWithPath(filePath);
//			}
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 登录， 自动处理cookie
	 * @param url
	 * @param username
	 * @param pwd
	 * @return
	 * @throws AppException
	 */
	public static User login(AppContext appContext,final String username,final String pwd) throws AppException {
		
		String loginurl = _MakeURL(URLs.MIHOME_LOGIN_VALIDATE_HTTP, new HashMap<String, Object>(){{
			put("username", username);
			put("password", pwd);
		}});
		
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, loginurl);
			User user=new User();
			Result result=new Result();
			if(responsePojo.getStatus()<0){
				result.setErrorCode(responsePojo.getStatus());
				result.setErrorMessage(responsePojo.getMsg());
				user.setValidate(result);
				return user;
			}else{
				user=User.parse(responsePojo.getData());	
				result.setErrorCode(1);
				user.setValidate(result);
				user.setToken(responsePojo.getMsg());
				//保存cookie   
        		if(appContext != null){
        			appContext.setProperty("cookie", "token="+responsePojo.getMsg());
                    String cookiestr=appContext.getProperty("cookie");
        			appCookie = "token="+responsePojo.getMsg();
        			PersistentCookieStore persistentCookieStore=(PersistentCookieStore) appContext.ASYNC_HTTP_CLIENT.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
        			BasicClientCookie basicClientCookie=new BasicClientCookie("token",responsePojo.getMsg());
        			basicClientCookie.setVersion(1);
        			basicClientCookie.setDomain("*");
        			Calendar calendar=Calendar.getInstance();
        			calendar.set(Calendar.YEAR,2015);
        			basicClientCookie.setExpiryDate(calendar.getTime());
        			persistentCookieStore.addCookie(basicClientCookie);
        		}
				return user;
			}
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

    /**
     * 异步登陆
     * */
    public static void loginAsync(final AppContext appContext,final String userName,final String pwd , final LoginResponseHandler loginResponseHandler){
        RequestParams requestParams=new RequestParams();
        requestParams.add("username",userName);
        requestParams.add("password",pwd);
        AppContext.ASYNC_HTTP_CLIENT.get(appContext,URLs.MIHOME_LOGIN_VALIDATE_HTTP,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, org.apache.http.Header[] arg1, ResponsePojo<Map> responsePojo) {
                User user=User.parse(responsePojo.getData());
                user.setToken(responsePojo.getMsg());
                user.setPwd(pwd);
                appContext.setProperty("cookie", "token="+responsePojo.getMsg());
                String cookiestr=appContext.getProperty("cookie");
                appCookie = "token="+responsePojo.getMsg();
                PersistentCookieStore persistentCookieStore=(PersistentCookieStore) appContext.ASYNC_HTTP_CLIENT.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
                BasicClientCookie basicClientCookie=new BasicClientCookie("token",responsePojo.getMsg());
                basicClientCookie.setVersion(1);
                basicClientCookie.setDomain("*");
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.YEAR,2015);
                basicClientCookie.setExpiryDate(calendar.getTime());
                persistentCookieStore.addCookie(basicClientCookie);
                appContext.saveLoginInfo(user);
                loginHx(user,pwd,loginResponseHandler);
            }
            @Override
            public void onFailure(int arg0, org.apache.http.Header[] arg1, Throwable arg3) {
                loginResponseHandler.onFailed(arg3.getMessage());
            }
        });
    }
    /**
     * 异步登录环信
     * */
    public static void loginHx(final User user,String pwd, final LoginResponseHandler loginResponseHandler){
        String openId=user.getOpenId();
        String pwd2=AppContext.getInstance().encnryPwd(pwd);
        EMChatManager.getInstance().login(openId,pwd2, new EMCallBack() {
            @Override
            public void onSuccess() {
                loginResponseHandler.onSuccess(user);
            }

            @Override
            public void onError(int i, String s) {
                loginResponseHandler.onFailed(s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }
  	/**
	 * 我的个人资料
	 * @param appContext
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static MyInformation myInformation(AppContext appContext, int uid) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_USER_INFO, new HashMap<String, Object>(){{
		}}); 
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return MyInformation.parse(responsePojo.getData());		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 我的个人资料
	 * @param appContext
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static void myInformation(AppContext appContext, final Integer uid,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler) {
        String newUrl  = _MakeURL(URLs.MIHOME_USER_FRIEND_INFO, new HashMap<String, Object>(){{
                put("uid",uid);
            }});
		PersistentCookieStore cc=(PersistentCookieStore) appContext.ASYNC_HTTP_CLIENT.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
		appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl,miAsyncHttpResponseHandler);
	}
    /**
     * 好友资料
     * @param appContext
     * @param uid
     * @return
     * @throws AppException
     */
    public static void friendInformation(AppContext appContext, final Integer uid,final String userName,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler) {
        String newUrl =null;
        if(uid!=null&&uid!=-1){
            newUrl = _MakeURL(URLs.MIHOME_USER_FRIEND_INFO, new HashMap<String, Object>(){{
                put("uid",uid);
            }});
        }else if(userName!=null&&!userName.trim().equals("")){
            newUrl = _MakeURL(URLs.MIHOME_USER_FRIEND_INFO_BY_NAME, new HashMap<String, Object>(){{
                put("name",userName);
            }});
        }
        PersistentCookieStore cc=(PersistentCookieStore) appContext.ASYNC_HTTP_CLIENT.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
        appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl,miAsyncHttpResponseHandler);
    }
    /**
     * 编辑个人信息
     * @param appContext
     * @param uid
     * @return
     * @throws AppException
     */
    public static void updateUser(final AppContext appContext, final String itemName,final String itemVlue ,MiAsyncHttpResponseHandler<Map> miAsyncHttpResponseHandler) {
        final User user=appContext.getLoginInfo();
        String newUrl = _MakeURL(URLs.MIHOME_USER_UPDATE, new HashMap<String, Object>(){{
            put(itemName,itemVlue);
            if(user!=null&&user.getToken()!=null){
                put("token",user.getToken());
            }
        }});
        PersistentCookieStore cc=(PersistentCookieStore) appContext.ASYNC_HTTP_CLIENT.getHttpContext().getAttribute(ClientContext.COOKIE_STORE);
        appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl,miAsyncHttpResponseHandler);
    }
	/**
	 * 更新用户头像
	 * @param appContext
	 * @param uid 当前用户uid
	 * @param portrait 新上传的头像
	 * @return
	 * @throws AppException
	 */
	public static Result updatePortrait(AppContext appContext, int uid, File portrait) throws AppException {
		
		try{
			/**
			 * 首先上传图片
			 * */
			Map<String, File> files = new HashMap<String, File>();
			final ResponsePojo imgPojo=new ResponsePojo();
			if(portrait != null){
				files.put("pic", portrait);
				ResponsePojo responsePojo=http_post_responsePojo(appContext, URLs.MIHOME_IMAGE_UPLOAD, new HashMap<String, Object>(), files);
                if(responsePojo.getStatus()<0){
                    throw new Exception("上传失败");
                }
				imgPojo.setMsg(responsePojo.getMsg());
			}
			String newUrl = _MakeURL(URLs.MIHOME_USER_UPDATE, new HashMap<String, Object>(){{
				if(imgPojo.getMsg()!=null){
					put("avatar",imgPojo.getMsg());
				}
			}});
				ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);
                if(pojo.getStatus()<0){
                    throw new Exception("上传失败");
                }
				Result result=new Result();
				result.setErrorMessage("修改成功");
				return result;
			}catch(Exception e){
				e.printStackTrace();
				if(e instanceof AppException)
					throw (AppException)e;
				throw AppException.network(e);
			}
	}
	
	/**
	 * 获取用户信息个人专页（包含该用户的动态信息以及个人信息）
	 * @param uid 自己的uid
	 * @param hisuid 被查看用户的uid
	 * @param hisname 被查看用户的用户名
	 * @param pageIndex 页面索引
	 * @param pageSize 每页读取的动态个数
	 * @return
	 * @throws AppException
	 */
	public static UserInformation information(AppContext appContext, int uid, int hisuid, String hisname, int pageIndex, int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("hisuid", hisuid);
		params.put("hisname", hisname);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);
				
		try{
			return UserInformation.parse(_post(appContext, URLs.USER_INFORMATION, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新用户之间关系（加关注、取消关注）
	 * @param uid 自己的uid
	 * @param hisuid 对方用户的uid
	 * @param newrelation 0:取消对他的关注 1:关注他
	 * @return
	 * @throws AppException
	 */
	public static Result updateRelation(AppContext appContext, int uid, int hisuid, int newrelation) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("hisuid", hisuid);
		params.put("newrelation", newrelation);
				
		try{
			return Result.parse(_post(appContext, URLs.USER_UPDATERELATION, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取用户通知信息
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static Notice getUserNotice(AppContext appContext, int uid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
				
		try{
			return Notice.parse(_post(appContext, URLs.USER_NOTICE, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 清空通知消息
	 * @param uid
	 * @param type 1:@我的信息 2:未读消息 3:评论个数 4:新粉丝个数
	 * @return
	 * @throws AppException
	 */
	public static Result noticeClear(AppContext appContext, int uid, int type) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("type", type);
				
		try{
			return Result.parse(_post(appContext, URLs.NOTICE_CLEAR, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户粉丝、关注人列表
	 * @param uid
	 * @param relation 0:显示自己的粉丝 1:显示自己的关注者
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static FriendList getFriendList(AppContext appContext, final int uid, final int relation, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.FRIENDS_LIST, new HashMap<String, Object>(){{
			put("uid", uid);
			put("relation", relation);
			put("pageIndex", pageIndex);
			put("pageSize", pageSize);
		}});
		
		try{
			return FriendList.parse(http_get(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	public static int convertPager(int pageIndex,int pageSize){
		if(pageIndex>0){
			pageIndex=pageIndex-1;
			return pageIndex*pageSize;
		}else{
			return pageIndex;
		}
	}
	/**
	 * 获取资讯列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<NewsType> getNewsTypeList(AppContext appContext,final int begin, final int num) throws AppException {
		final String last_time;
		if(appContext.getProperty("last_time")!=null){
			 last_time=appContext.getProperty("last_time");
		}else{
			String nowLong=""+System.currentTimeMillis();
			appContext.setProperty("last_time",nowLong);
			last_time=nowLong;
		}
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_TYPE_LIST, new HashMap<String, Object>(){{
			put("last_time", last_time);
			put("begin",begin);
			put("num", num);
		}});
		try{
			return NewsType.parseList(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取资讯列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static NewsList getNewsList(AppContext appContext, final int typeId, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_LIST, new HashMap<String, Object>(){{
			put("type_id", typeId);
			put("begin",convertPager(pageIndex,pageSize));
			put("num", pageSize);
		}});
		try{
			return NewsList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取文章列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<Article> getArticleList(AppContext appContext, final int typeId, final int begin, final int num,final String titleSearchString) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_ARTICLE_LIST, new HashMap<String, Object>(){{
				put("type_id", typeId);
				
				put("begin",begin);
				put("num", num);
				if(titleSearchString!=null&&!titleSearchString.trim().equals("")){
					put("title", URLEncoder.encode(titleSearchString,"UTF-8"));
				}
			}});
			return Article.parseList(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取文章详情
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static Article getArticleDetail(AppContext appContext, final int articleId) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_ARTICLE_DETAIL, new HashMap<String, Object>(){{
			put("id", articleId);
		}});
		try{
			return Article.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取资讯列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static NewsList getNewsList2(AppContext appContext, final int typeId, final int begin, final int num) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_LIST, new HashMap<String, Object>(){{
			put("type_id", typeId);
			put("begin",begin);
			put("num", num);
		}});
		try{
			return NewsList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取聊天房间列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<ChatRoom> getChatRoomList(AppContext appContext, final int begin, final int num,int type) throws AppException {
		String urlmodel="";
		switch (type) {
		case ChatRoom.MY:
			urlmodel=URLs.MIHOME_CHAT_ROOM_LIST_MY;
			break;
		default:
			urlmodel=URLs.MIHOME_CHAT_ROOM_LIST;
			break;
		}
		String newUrl = _MakeURL(urlmodel, new HashMap<String, Object>(){{
			put("begin",begin);
			put("num", num);
		}});
		try{
			return ChatRoom.parseList(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 修改密码
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static boolean resetPassWord(AppContext appContext,final String username,final String passWord) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_USER_REST_PASSWORD, new HashMap<String, Object>(){{
			put("username",username);
			put("password", passWord);
		}});
		try{
			ResponsePojo response=http_get_responsePojo(appContext, newUrl);
			if(response==null||response.getStatus()<0){
				return false;
			}else{
				return true;
			}
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 根据用户名找手机号
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static String getPhoneByUsername(AppContext appContext,final String username) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_USER_GET_PHONE_BY_USERNAME, new HashMap<String, Object>(){{
			put("username",username);
		}});
		try{
			ResponsePojo<String> response=http_get_responsePojo(appContext, newUrl);
			if(response==null||response.getStatus()<0){
				return null;
			}else{
				return response.getData();
			}
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取聊天记录
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<ChatMsgEntity> getChatRecordList(AppContext appContext,final int room_id, final int begin, final int num) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_CHAT_TALK_TALK_LIST, new HashMap<String, Object>(){{
			put("begin",begin);
			put("num", num);
			put("room_id", room_id);
		}});
		try{
			return ChatMsgEntity.parseList(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 添加聊天房间
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static ResponsePojo addChatRoom(AppContext appContext, final String name,final String desc,final String time,final String peopel_num) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_CHAT_ROOM_ADD, new HashMap<String, Object>(){{
				put("name",URLEncoder.encode(name,"utf-8"));
				put("desc",URLEncoder.encode(desc,"utf-8"));
				put("time",URLEncoder.encode(time,"utf-8"));
				put("people_num",URLEncoder.encode(peopel_num,"utf-8"));
			}});
			return http_get_responsePojo(appContext, newUrl);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 添加聊天房间
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static ResponsePojo joinRoom(AppContext appContext, final String room_id) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_CHAT_ROOM_JOINROOM, new HashMap<String, Object>(){{
				put("room_id",room_id);
			}});
			return http_get_responsePojo(appContext, newUrl);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	public static ResponsePojo leavelRoom(AppContext appContext, final String room_id) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_CHAT_ROOM_LEAVELROOM, new HashMap<String, Object>(){{
				put("room_id",room_id);
			}});
			return http_get_responsePojo(appContext, newUrl);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	public static ResponsePojo delRoom(AppContext appContext, final String room_id) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_CHAT_ROOM_DELROOM, new HashMap<String, Object>(){{
				put("room_id",room_id);
			}});
			return http_get_responsePojo(appContext, newUrl);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 聊天发言
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<ChatMsgEntity> addTalk(AppContext appContext, final String user_name,final int room_id ,final String content) throws AppException {
		try{
			String newUrl = _MakeURL(URLs.MIHOME_CHAT_TALK_TALK_ADD, new HashMap<String, Object>(){{
				put("user_name",URLEncoder.encode(user_name,"utf-8"));
				put("content",URLEncoder.encode(content,"utf-8"));
				put("room_id",room_id);
			}});
			return ChatMsgEntity.parseList(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取资讯列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<RssNews> getRssNewsList(AppContext appContext, RssResource rssResource, final int pageIndex, final int pageSize) throws AppException {
		try{
			String xmlStr=URLs.readFromInputStream(http_get(appContext, rssResource.getHref()));
			return RssNews.parse(xmlStr);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取区域列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static CommunityList getArea(AppContext appContext, final int parentid) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_COMMINUTY_LIST, new HashMap<String, Object>(){{
			put("parentid", parentid);
		}});
		try{
			return CommunityList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取资讯的详情
	 * @param url
	 * @param news_id
	 * @return
	 * @throws AppException
	 */
	public static News getNewsDetail(AppContext appContext, final int news_id) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_DETAIL, new HashMap<String, Object>(){{
			put("id", news_id);
		}});
		
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return News.parse(responsePojo.getData());			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取资讯的详情
	 * @param url
	 * @param news_id
	 * @return
	 * @throws AppException
	 */
	public static Banner getBanner(AppContext appContext) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_DETAIL, new HashMap<String, Object>(){{
		}});
		try{
//			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return Banner.parse(null);			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 检查用户名是否存在
	 * @param url
	 * @param news_id
	 * @return
	 * @throws AppException
	 */
	public static ResponsePojo checkUserName(AppContext appContext, final String userName) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_REGISTER_CHECK_USERNAME, new HashMap<String, Object>(){{
			put("username", userName);
		}});
		
		try{
			ResponsePojo responsePojo=http_get_responsePojo(appContext, newUrl);
			return responsePojo;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 注册
	 * @param url
	 * @param news_id
	 * @return
	 * @throws AppException
	 */
	public static ResponsePojo register(AppContext appContext, final String username ,final String mobile  ,final String password ,final String community_id,final String buildingid  ) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_REGISTER, new HashMap<String, Object>(){{
			put("username", username);
			put("mobile", mobile);
			put("password", password);
			put("buildingid", buildingid);
			put("community_id", community_id);
		}});
		
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return responsePojo;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取商店的详情
	 * @param url
	 * @param news_id
	 * @return
	 * @throws AppException
	 */
	public static Shop getShopDetail(AppContext appContext, final int shop_id) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_SHOP_DETAIL, new HashMap<String, Object>(){{
			put("id", shop_id);
		}});
		
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return Shop.parse(responsePojo.getData());			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取某用户的博客列表
	 * @param authoruid
	 * @param uid
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static BlogList getUserBlogList(AppContext appContext, final int authoruid, final String authorname, final int uid, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.USERBLOG_LIST, new HashMap<String, Object>(){{
			put("authoruid", authoruid);
			put("authorname", URLEncoder.encode(authorname));
			put("uid", uid);
			put("pageIndex", pageIndex);
			put("pageSize", pageSize);
		}});

		try{
			return BlogList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取博客列表
	 * @param type 推荐：recommend 最新：latest
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static BlogList getBlogList(AppContext appContext, final String type, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_LIST, new HashMap<String, Object>(){{
			put("type_id", NewsList.NEWS_TYPE_TUIJIANYUEDU);
			put("begin",convertPager(pageIndex,pageSize));
			put("num", pageSize);
		}});
		try{
			return BlogList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除某用户的博客
	 * @param uid
	 * @param authoruid
	 * @param id
	 * @return
	 * @throws AppException
	 */
	public static Result delBlog(AppContext appContext, int uid, int authoruid, int id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("authoruid", authoruid);
		params.put("id", id);

		try{
			return http_post(appContext, URLs.USERBLOG_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取博客详情
	 * @param blog_id
	 * @return
	 * @throws AppException
	 */
	public static RssType getBlogDetail(AppContext appContext, final int blog_id) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_NEWS_DETAIL, new HashMap<String, Object>(){{
			put("id", blog_id);
		}});
		
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return RssType.parse(responsePojo.getData());			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取帖子列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static PostList getPostList(AppContext appContext, final int catalog, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_LIST, new HashMap<String, Object>(){{
			put("begin", convertPager(pageIndex, pageSize));
			put("num", pageSize);
		}});

		try{
			return PostList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取报业主修列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static PostList getRepairReauestList(AppContext appContext, final int begin, final int num) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_LIST, new HashMap<String, Object>(){{
			put("begin", begin);
			put("num", num);
		}});

		try{
			return PostList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 通过Tag获取帖子列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static PostList getPostListByTag(AppContext appContext, final String tag, final int pageIndex, final int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("tag", tag);
		params.put("begin", convertPager(pageIndex, pageSize));
		params.put("num", pageSize);		

		try{
			return PostList.parse(http_post_responsePojo(appContext, URLs.POST_LIST, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取帖子的详情
	 * @param url
	 * @param post_id
	 * @return
	 * @throws AppException
	 */
	public static Post getPostDetail(AppContext appContext, final int post_id) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_DETAIL, new HashMap<String, Object>(){{
			put("id", post_id);
		}});
		try{

			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return Post.parse(responsePojo.getData());			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 保存用户属性到服务器上
	 * @param post （uid、title、catalog、content、isNoticeMe）
	 * @return
	 * @throws AppException
	 */
	public static Result setUserPropertie(AppContext appContext,final String key,final String value) throws AppException {		
		try{	
			String newUrl = _MakeURL(URLs.MIHOME_USER_PROPERTIE_SET, new HashMap<String, Object>(){{
				put("key",URLEncoder.encode(key,"UTF-8"));
				put("value",URLEncoder.encode(value,"UTF-8"));
			}});
			ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);	
			Result result=new Result();
			result.setErrorMessage("发表成功");
			return result;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 保存用户属性到服务器上
	 * @param post （uid、title、catalog、content、isNoticeMe）
	 * @return
	 * @throws AppException
	 */
	public static UserPrepertie getUserPropertie(AppContext appContext,final String key) throws AppException {		
		try{	
			String newUrl = _MakeURL(URLs.MIHOME_USER_PROPERTIE_GET, new HashMap<String, Object>(){{
				put("key",URLEncoder.encode(key,"UTF-8"));
			}});
			ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);
			if(pojo!=null&&pojo.getData()!=null){
				return UserPrepertie.parse((Map) pojo.getData());
			}
			return null;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 发帖子
	 * @param post （uid、title、catalog、content、isNoticeMe）
	 * @return
	 * @throws AppException
	 */
	public static Result pubPost(AppContext appContext,final Post post) throws AppException {		
		try{	
			String newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_ADD, new HashMap<String, Object>(){{
				put("content",URLEncoder.encode(post.getCatalogName(),"utf-8"));
				put("mark",URLEncoder.encode(post.getBody(),"utf-8"));
			}});
			ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);	
			Result result=new Result();
			result.setErrorMessage("发表成功");
			return result;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取动弹列表
	 * @param uid
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static TweetList getTweetList(AppContext appContext, final int uid, final int communityId,final int pageIndex, final int pageSize) throws AppException {
		String newUrl="";
		if(uid>0){
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_MY, new HashMap<String, Object>(){{
				put("uid", uid);
				put("begin", convertPager(pageIndex, pageSize));
				put("num", pageSize);
				put("community_id", communityId);
			}});
		}else if(uid<0){
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_HOT, new HashMap<String, Object>(){{
				put("begin", convertPager(pageIndex, pageSize));
				put("num", pageSize);
			}});
		}else{
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST, new HashMap<String, Object>(){{
				put("begin", convertPager(pageIndex, pageSize));
				put("num", pageSize);
			}});
		}
		
		try{
			return TweetList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取动弹列表
	 * @param uid
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static TweetList getTweetList2(AppContext appContext, final int uid, final int begin, final int num) throws AppException {
		String newUrl="";
		if(uid>0){
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_MY, new HashMap<String, Object>(){{
				put("uid", uid);
				put("begin", begin);
				put("num", num);
			}});
		}else if(uid<0){
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_HOT, new HashMap<String, Object>(){{
				put("begin", begin);
				put("num", num);
			}});
		}else{
			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST, new HashMap<String, Object>(){{
				put("begin", begin);
				put("num", num);
			}});
		}
		
		try{
			return TweetList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取动弹列表
	 * @param uid
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static void getTweetListAnsy(AppContext appContext, final int toUid,final int uid, final int communityId,final int begin, final int num,MiAsyncHttpResponseHandler asyncHttpResponseHandler) {
		String newUrl="";
        newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST, new HashMap<String, Object>(){{
            put("begin", begin);
            put("num", num);
            put("uid", uid);
			put("to_uid", toUid);
            put("community_id", communityId);
        }});
//		if(toUid>0){
//			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_MY, new HashMap<String, Object>(){{
//				put("uid", uid);
//				put("to_uid", toUid);
//				put("begin", begin);
//				put("num", num);
//                put("community_id", communityId);
//			}});
//		}else if(uid<0){
//			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_HOT, new HashMap<String, Object>(){{
//				put("begin", begin);
//				put("num", num);
//				put("uid", uid);
//                put("community_id", communityId);
//			}});
//		}else{
//			newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST, new HashMap<String, Object>(){{
//				put("begin", begin);
//				put("num", num);
//                put("uid", uid);
//                put("community_id", communityId);
//			}});
//		}
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
		appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl, requestParams,asyncHttpResponseHandler);
	}
    /**
     *赞大字报
     */
    public static void supportTweetAnsy(AppContext appContext, final int uid,final String userNmae, final int bigpaperId,MiAsyncHttpResponseHandler asyncHttpResponseHandler) {
        String newUrl="";
            newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_SUPPORT, new HashMap<String, Object>(){{
                put("uid", uid);
                put("paper_id", bigpaperId);
                put("username", userNmae);
            }});
        appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl, asyncHttpResponseHandler);
    }
    /**
     *删除
     */
    public static void deleteBigPaper(AppContext appContext, final int bigpaperId,MiAsyncHttpResponseHandler asyncHttpResponseHandler) {
        String newUrl="";
        newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_DELETE, new HashMap<String, Object>(){{
            put("id", bigpaperId);
        }});
        appContext.ASYNC_HTTP_CLIENT.get(appContext, newUrl, asyncHttpResponseHandler);
    }
	/**
	 * 获取动弹详情
	 * @param tweet_id
	 * @return
	 * @throws AppException
	 */
	public static Tweet getTweetDetail(AppContext appContext, final int tweet_id) throws AppException {
		String newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_DETAIL, new HashMap<String, Object>(){{
			put("id", tweet_id);
		}});
		try{
			ResponsePojo<Map> responsePojo=http_get_responsePojo(appContext, newUrl);
			return Tweet.parse(responsePojo.getData());			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
    /**
     * 上传群图片
     * */
    public static String uploadImage(AppContext appContext,final File file,final String name) throws Exception {
        Map<String, File> files = new HashMap<String, File>();
        files.put("pic", file);
        ResponsePojo responsePojo=http_post_responsePojo(appContext, URLs.MIHOME_GROUP_AVATAR_UPLOAD+"?group_id="+name, new HashMap<String, Object>(), files);
        if(responsePojo!=null){
            return responsePojo.getMsg();
        }else{
            return null;
        }
    }
    /**
     * 上传图片
     * */
    public static String uploadImage(AppContext appContext,final File file) throws Exception {
        Map<String, File> files = new HashMap<String, File>();
        files.put("pic", file);
        ResponsePojo responsePojo=http_post_responsePojo(appContext, URLs.MIHOME_IMAGE_UPLOAD, new HashMap<String, Object>(), files);
        if(responsePojo!=null){
            return responsePojo.getMsg();
        }else{
            return null;
        }
    }
 	/**
	 * 发动弹
	 * @param Tweet-uid & msg & image
	 * @return
	 * @throws AppException
	 */
	public static Result pubTweet(AppContext appContext, final Tweet tweet) throws AppException {

		try{
		/**
		 * 首先上传图片
		 * */
		final StringBuffer imgUrls=new StringBuffer();
		if(tweet.getImageFiles() != null){
            Iterator<File> iterator=tweet.getImageFiles().iterator();
            while(iterator.hasNext()){
                File file=iterator.next();
                Map<String, File> files = new HashMap<String, File>();
                files.put("pic", file);
                ResponsePojo responsePojo=http_post_responsePojo(appContext, URLs.MIHOME_IMAGE_UPLOAD, new HashMap<String, Object>(), files);
                imgUrls.append(";").append(responsePojo.getMsg());
            }
		}
            final Result result=new Result();
            result.setErrorMessage("发表成功");
            RequestParams tweetDetail=new RequestParams();
            User user=AppContext.getInstance().getLoginInfo();
            tweetDetail.put("uid",user.getUid()+"");
            tweetDetail.put("parentid",0+"");
            tweetDetail.put("text",tweet.getBody());
            tweetDetail.put("username",user.getAccount());
            tweetDetail.put("token",user.getToken());
            tweetDetail.put("community_id",user.getCommunityId());
            if(imgUrls.length()>0){
                String stringImgs=imgUrls.toString();
                stringImgs=stringImgs.substring(1);
                tweetDetail.put("imgs",stringImgs);
            }
            appContext.SYNC_HTTP_CLIENT.post(appContext,URLs.MIHOME_ADD_BIGPAPER,tweetDetail,new MiAsyncHttpResponseHandler<Map>() {
                @Override
                public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                    result.setErrorMessage("张贴成功");
                }

                @Override
                public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                    result.setErrorCode(arg0);
                    result.setErrorMessage("张贴失败");
                }
            });
			return result;
		}catch(Exception e){
			e.printStackTrace();
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 发动弹
	 * @return
	 * @throws AppException
	 */
	public static Result pubBaoxiu(AppContext appContext, final Tweet tweet) throws AppException {

		try{
		/**
		 * 首先上传图片
		 * */
		Map<String, File> files = new HashMap<String, File>();
		final ResponsePojo imgPojo=new ResponsePojo();
		if(tweet.getImageFiles() != null){
			files.put("pic", tweet.getImageFiles().get(0));
			ResponsePojo responsePojo=http_post_responsePojo(appContext, URLs.MIHOME_IMAGE_UPLOAD, new HashMap<String, Object>(), files);
			imgPojo.setMsg(responsePojo.getMsg());
		}
		String newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_ADD, new HashMap<String, Object>(){{
			put("content",URLEncoder.encode(tweet.getAttach(),"utf-8"));
			put("mark",URLEncoder.encode(tweet.getBody(),"utf-8"));
			put("username","aydx84318");
			if(imgPojo.getMsg()!=null){
				put("imgs",imgPojo.getMsg());
			}
		}});
			ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);	
			Result result=new Result();
			result.setErrorMessage("发表成功");
			return result;
		}catch(Exception e){
			e.printStackTrace();
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 删除动弹
	 * @param uid
	 * @param tweetid
	 * @return
	 * @throws AppException
	 */
	public static Result delTweet(AppContext appContext, int uid, int tweetid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("tweetid", tweetid);

		try{
			return http_post(appContext, URLs.TWEET_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取动态列表
	 * @param uid
	 * @param catalog 1最新动态  2@我  3评论  4我自己 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static ActiveList getActiveList(AppContext appContext, final int uid,final int catalog, final int pageIndex, final int pageSize) throws AppException {
		
		String newUrl="";
			newUrl = _MakeURL(URLs.MIHOME_GET_REPAIR_LIST, new HashMap<String, Object>(){{
				put("begin", convertPager(pageIndex, pageSize));
				put("num", pageSize);
			}});
		
		try{
			return ActiveList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取广告列表
	 * @param uid
	 * @param catalog 1最新动态  2@我  3评论  4我自己 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static AdvertList getAdvertList(AppContext appContext, final int uid,final int catalog, final int pageIndex, final int pageSize) throws AppException {
		String newUrl="";
			newUrl = _MakeURL(URLs.MIHOME_GET_ADVERT_LIST, new HashMap<String, Object>(){{
//				put("lat", convertPager(pageIndex, pageSize));
//				put("lon", pageSize);
//				put("radius", pageSize);
				put("begin", convertPager(pageIndex, pageSize));
				put("num", pageSize);
			}});
		
		try{
			return AdvertList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取广告列表
	 * @param uid
	 * @param catalog 1最新动态  2@我  3评论  4我自己 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static List<ShopMenu> getShopMenus(AppContext appContext, final int shop_id,final int begin, final int num) throws AppException {
		String newUrl="";
			newUrl = _MakeURL(URLs.MIHOME_GET_SHOP_MENU, new HashMap<String, Object>(){{
				put("begin", begin);
				put("num", num);
				put("id",shop_id);
			}});
		
		try{
			return ShopMenu.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取广告列表
	 * @param uid
	 * @param catalog 1最新动态  2@我  3评论  4我自己 
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static AdvertList getAdvertList2(AppContext appContext, final int begin, final int num) throws AppException {
		String newUrl="";
			newUrl = _MakeURL(URLs.MIHOME_GET_ADVERT_LIST, new HashMap<String, Object>(){{
				put("begin", begin);
				put("num", num);
			}});
		try{
			return AdvertList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取留言列表
	 * @param uid
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static MessageList getMessageList(AppContext appContext, final int uid, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.MESSAGE_LIST, new HashMap<String, Object>(){{
			put("uid", uid);
			put("pageIndex", pageIndex);
			put("pageSize", pageSize);
		}});
		
		try{
			return MessageList.parse(http_get(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 发送留言
	 * @param uid 登录用户uid
	 * @param receiver 接受者的用户id
	 * @param content 消息内容，注意不能超过250个字符
	 * @return
	 * @throws AppException
	 */
	public static Result pubMessage(AppContext appContext, int uid, int receiver, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("receiver", receiver);
		params.put("content", content);

		try{
			return http_post(appContext, URLs.MESSAGE_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 转发留言
	 * @param uid 登录用户uid
	 * @param receiver 接受者的用户名
	 * @param content 消息内容，注意不能超过250个字符
	 * @return
	 * @throws AppException
	 */
	public static Result forwardMessage(AppContext appContext, int uid, String receiverName, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("receiverName", receiverName);
		params.put("content", content);

		try{
			return http_post(appContext, URLs.MESSAGE_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除留言
	 * @param uid 登录用户uid
	 * @param friendid 留言者id
	 * @return
	 * @throws AppException
	 */
	public static Result delMessage(AppContext appContext, int uid, int friendid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("friendid", friendid);

		try{
			return http_post(appContext, URLs.MESSAGE_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取博客评论列表
	 * @param id 博客id
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static BlogCommentList getBlogCommentList(AppContext appContext, final int id, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.BLOGCOMMENT_LIST, new HashMap<String, Object>(){{
			put("id", id);
			put("pageIndex", pageIndex);
			put("pageSize", pageSize);
		}});
		
		try{
			return BlogCommentList.parse(http_get(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 发表博客评论
	 * @param blog 博客id
	 * @param uid 登陆用户的uid
	 * @param content 评论内容
	 * @return
	 * @throws AppException
	 */
	public static Result pubBlogComment(AppContext appContext, int blog, int uid, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("blog", blog);
		params.put("uid", uid);
		params.put("content", content);
		
		try{
			return http_post(appContext, URLs.BLOGCOMMENT_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 发表博客评论
	 * @param blog 博客id
	 * @param uid 登陆用户的uid
	 * @param content 评论内容
	 * @param reply_id 评论id
	 * @param objuid 被评论的评论发表者的uid
	 * @return
	 * @throws AppException
	 */
	public static Result replyBlogComment(AppContext appContext, int blog, int uid, String content, int reply_id, int objuid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("blog", blog);
		params.put("uid", uid);
		params.put("content", content);
		params.put("reply_id", reply_id);
		params.put("objuid", objuid);
		
		try{
			return http_post(appContext, URLs.BLOGCOMMENT_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除博客评论
	 * @param uid 登录用户的uid
	 * @param blogid 博客id
	 * @param replyid 评论id
	 * @param authorid 评论发表者的uid
	 * @param owneruid 博客作者uid
	 * @return
	 * @throws AppException
	 */
	public static Result delBlogComment(AppContext appContext, int uid, int blogid, int replyid, int authorid, int owneruid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blogid", blogid);		
		params.put("replyid", replyid);
		params.put("authorid", authorid);
		params.put("owneruid", owneruid);

		try{
			return http_post(appContext, URLs.BLOGCOMMENT_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取评论列表
	 * @param catalog 1新闻  2帖子  3动弹  4动态
	 * @param id
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static CommentList getCommentList(AppContext appContext, final int catalog, final int id, final int pageIndex, final int pageSize) throws AppException {
		final User user=appContext.getLoginInfo();
        String newUrl = _MakeURL(URLs.MIHOME_GET_BIGPAPER_LIST_COMMENT, new HashMap<String, Object>(){{
//			put("catalog", catalog);
			put("id", id);
			put("parent_id", id);
			put("begin", convertPager(pageIndex, pageSize));
			put("num", pageSize);
            if(user!=null){
                put("community_id",user.getCommunityId());
            }
		}});
		
		try{
			return CommentList.parse(http_get_responsePojo(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 发表评论
	 * @param catalog 1新闻  2帖子  3动弹  4动态
	 * @param id 某条新闻，帖子，动弹的id
	 * @param uid 用户uid
	 * @param content 发表评论的内容
	 * @param isPostToMyZone 是否转发到我的空间  0不转发  1转发
	 * @return
	 * @throws AppException
	 * @throws UnsupportedEncodingException 
	 */
	public static Result pubComment(AppContext appContext,final int catalog, final int id,final int uid,final String content, int isPostToMyZone) throws AppException {

        final User user=appContext.getLoginInfo();
		try{
		String newUrl = _MakeURL(URLs.MIHOME_ADD_BIGPAPER, new HashMap<String, Object>(){{
			put("uid",uid);
			put("parentid",id);
			put("text",URLEncoder.encode(content,"utf-8"));
			put("username", user.getName());
            if(user!=null){
                put("community_id", user.getCommunityId());
            }
		}});
			ResponsePojo pojo= http_get_responsePojo(appContext, newUrl);	
			Result result=new Result();
			result.setErrorMessage("发表成功");
			result.setErrorCode(1);
		//
			return result;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 
	 * @param id 表示被评论的某条新闻，帖子，动弹的id 或者某条消息的 friendid 
	 * @param catalog 表示该评论所属什么类型：1新闻  2帖子  3动弹  4动态
	 * @param replyid 表示被回复的单个评论id
	 * @param authorid 表示该评论的原始作者id
	 * @param uid 用户uid 一般都是当前登录用户uid
	 * @param content 发表评论的内容
	 * @return
	 * @throws AppException
	 */
	public static Result replyComment(AppContext appContext, int id, int catalog, int replyid, int authorid, int uid, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("id", id);
		params.put("uid", uid);
		params.put("content", content);
		params.put("replyid", replyid);
		params.put("authorid", authorid);
		
		try{
			return http_post(appContext, URLs.COMMENT_REPLY, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除评论
	 * @param id 表示被评论对应的某条新闻,帖子,动弹的id 或者某条消息的 friendid
	 * @param catalog 表示该评论所属什么类型：1新闻  2帖子  3动弹  4动态&留言
	 * @param replyid 表示被回复的单个评论id
	 * @param authorid 表示该评论的原始作者id
	 * @return
	 * @throws AppException
	 */
	public static Result delComment(AppContext appContext, int id, int catalog, int replyid, int authorid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("id", id);
		params.put("catalog", catalog);
		params.put("replyid", replyid);
		params.put("authorid", authorid);

		try{
			return http_post(appContext, URLs.COMMENT_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户收藏列表
	 * @param uid 用户UID
	 * @param type 0:全部收藏 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @param pageIndex 页面索引 0表示第一页
	 * @param pageSize 每页的数量
	 * @return
	 * @throws AppException
	 */
	public static FavoriteList getFavoriteList(AppContext appContext, final int uid, final int type, final int pageIndex, final int pageSize) throws AppException {
		String newUrl = _MakeURL(URLs.FAVORITE_LIST, new HashMap<String, Object>(){{
			put("uid", uid);
			put("type", type);
			put("pageIndex", pageIndex);
			put("pageSize", pageSize);
		}});
		
		try{
			return FavoriteList.parse(http_get(appContext, newUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}	
	
	/**
	 * 用户添加收藏
	 * @param uid 用户UID
	 * @param objid 比如是新闻ID 或者问答ID 或者动弹ID
	 * @param type 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @return
	 * @throws AppException
	 */
	public static Result addFavorite(AppContext appContext, int uid, int objid, int type) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("objid", objid);
		params.put("type", type);

		try{
			return http_post(appContext, URLs.FAVORITE_ADD, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户删除收藏
	 * @param uid 用户UID
	 * @param objid 比如是新闻ID 或者问答ID 或者动弹ID
	 * @param type 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @return
	 * @throws AppException
	 */
	public static Result delFavorite(AppContext appContext, int uid, int objid, int type) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("objid", objid);
		params.put("type", type);

		try{
			return http_post(appContext, URLs.FAVORITE_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取搜索列表
	 * @param catalog 全部:all 新闻:news  问答:post 软件:software 博客:blog 代码:code
	 * @param content 搜索的内容
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static SearchList getSearchList(AppContext appContext, String catalog, String content, int pageIndex, int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("content", content);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);

		try{
			return SearchList.parse(_post(appContext, URLs.SEARCH_LIST, params, null));	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 软件列表
	 * @param searchTag 软件分类  推荐:recommend 最新:time 热门:view 国产:list_cn
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static SoftwareList getSoftwareList(AppContext appContext,final String searchTag,final int pageIndex,final int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("searchTag", searchTag);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);
		
		try{
			return SoftwareList.parse(_post(appContext, URLs.SOFTWARE_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 软件分类的软件列表
	 * @param searchTag 从softwarecatalog_list获取的tag
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static SoftwareList getSoftwareTagList(AppContext appContext,final int searchTag,final int pageIndex,final int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("searchTag", searchTag);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);

		try{
			return SoftwareList.parse(_post(appContext, URLs.SOFTWARETAG_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 软件分类列表
	 * @param tag 第一级:0  第二级:tag
	 * @return
	 * @throws AppException
	 */
	public static SoftwareCatalogList getSoftwareCatalogList(AppContext appContext,final int tag) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("tag", tag);

		try{
			return SoftwareCatalogList.parse(_post(appContext, URLs.SOFTWARECATALOG_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 发送短信验证码(注册用，手机号存在则发送失败)
	 * @throws AppException 
	 * */
	public static ResponsePojo sendPhoneMsg(AppContext appContext,final String phoneNum) throws AppException{
		String newUrl = _MakeURL(URLs.MIHOME_SEND_PHONE_SEND_CODE, new HashMap<String, Object>(){{
			put("mobile", phoneNum);
		}});
		try{
			ResponsePojo responsePojo= http_get_responsePojo(appContext, newUrl);	
			return responsePojo;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
    /**
     * 发送短信验证码(注册用，手机号存在则发送失败)
     * @throws AppException
     * */
    public static ResponsePojo sendPhoneMsgExists(AppContext appContext,final String phoneNum) throws AppException{
        String newUrl = _MakeURL(URLs.MIHOME_SEND_PHONE_SEND_CODE_EXISTS, new HashMap<String, Object>(){{
            put("mobile", phoneNum);
        }});
        try{
            ResponsePojo responsePojo= http_get_responsePojo(appContext, newUrl);
            return responsePojo;
        }catch(Exception e){
            if(e instanceof AppException)
                throw (AppException)e;
            throw AppException.network(e);
        }
    }
	/**
	 * 校验短信验证码
	 * @throws AppException 
	 * */
	public static ResponsePojo checkPhoneMsg(AppContext appContext,final String mobile,final String num) throws AppException{
		try{
			String newUrl = _MakeURL(URLs.MIHOME_SEND_PHONE_CHECK, new HashMap<String, Object>(){{
			put("num", num);
			put("mobile",mobile);
			}});
			ResponsePojo responsePojo= http_get_responsePojo(appContext, newUrl);	
			return responsePojo;
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	/**
	 * 获取软件详情
	 * @param ident
	 * @return
	 * @throws AppException
	 */
	public static Software getSoftwareDetail(AppContext appContext, final String ident) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("ident", ident);
		
		try{
			return Software.parse(_post(appContext, URLs.SOFTWARE_DETAIL, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 发送举报
	 * @param appContext
	 * @param report
	 * @return
	 * @throws AppException
	 */
	public static String report(AppContext appContext, Report report) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("obj_id", report.getReportId());
		params.put("url", report.getLinkAddress());
		params.put("obj_type", report.getReason());
		if (report.getOtherReason() != null) {
			params.put("memo", report.getOtherReason());
		} else {
			params.put("memo", "其他原因");
		}
		try{
			return StringUtils.toConvertString(_post(appContext, URLs.REPORT, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 二维码扫描签到
	 * @param appContext
	 * @param barcode
	 * @return
	 * @throws AppException
	 */
	public static String signIn(AppContext appContext, Barcode barcode) throws AppException {
		try{
			return StringUtils.toConvertString(http_get(appContext, barcode.getUrl()));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	} 
}
